﻿namespace WebPacker.Tool.Sources
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using WebPacker.Configuration;
	using WebPacker.Packs;

	internal class FilesSource : ISource
	{
		private readonly string[] fileNames;
		private readonly Configuration configuration;
		private readonly string packName;
		private PackInfo[] packs;

		public FilesSource(Configuration configuration, string[] fileNames)
			: this(configuration, "pack", fileNames)
		{
		}

		public FilesSource(Configuration configuration, string packName, string[] fileNames)
		{
			this.packName = packName;
			this.fileNames = fileNames;
			this.configuration = configuration;
		}

		public PackInfo[] Packs
		{
			get { return packs; }
		}

		public Configuration Configuration
		{
			get { return configuration; }
		}

		public void Open()
		{
			var packType = PackType.Unknown;
			var resources = new List<ResourceInfo>();

			foreach (var fileName in fileNames)
			{
				if (fileName.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase))
				{
					if (packType != PackType.Unknown && packType != PackType.JavaScript)
					{
						throw ToolException.DifferentTypes();
					}

					packType = PackType.JavaScript;
				}
				else if (fileName.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
				{
					if (packType != PackType.Unknown && packType != PackType.Css)
					{
						throw ToolException.DifferentTypes();
					}

					packType = PackType.Css;
				}

				resources.Add(new ResourceInfo { Name = fileName });
			}

			var pack = new PackInfo
			{
				Resources = resources.ToArray(),
				PackType = packType,
				Name = packName
			};

			packs = new PackInfo[] { pack };
		}
	}
}
